package com.abigdreamer.im.server.module;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import com.abigdreamer.im.server.log.EIMLogger;
import com.abigdreamer.im.server.module.socketHandler.ChatSocketHandler;
import com.abigdreamer.im.server.serverConfig.Config;
import com.abigdreamer.im.server.serverConfig.EIMChatSocketConfig;

/**
 * EIMChatSocket为负责转发用户的字符信息
 */
public class EIMChatSocket extends EIMSocket implements ISockect {

	private EIMChatSocketConfig chatSocketConfig;

	public EIMChatSocket(EIMChatSocketConfig config) {
		this.chatSocketConfig = config;
	}

	public boolean closeSocket() {
		this.getAcceptor().dispose();
		this.setStart(false);
		EIMLogger.INFO("关闭了 聊天消息Socket");
		return false;
	}

	public boolean initSocket(Config config) {
		EIMLogger.INFO("正在初始化 聊天Socket");
		EIMChatSocketConfig chatConfig = (EIMChatSocketConfig) config;
		this.setSocket_IP(chatConfig.getIp());
		EIMLogger.INFO("正在初始化 聊天Socket的Ip");
		this.setSocket_port(chatConfig.getPost());
		EIMLogger.INFO("正在初始化 聊天Sockett的端口");
		this.setHandlerAdapter(new ChatSocketHandler());
		EIMLogger.INFO("正在初始化 聊天Socket的处理器");
		this.setAcceptor(new NioSocketAcceptor());
		EIMLogger.INFO("正在初始化 聊天Socket的接收器");

		EIMLogger.INFO("成功初始化 聊天Socket");
		EIMLogger.INFO("聊天Socket服务IP:" + this.getSocket_IP());
		EIMLogger.INFO("聊天Socket服务端口号:" + this.getSocket_port());
		return true;
	}

	public boolean startSocket() {
		boolean result = false;
		if (this.isStart() == false) {
			initSocket(this.chatSocketConfig);
			DefaultIoFilterChainBuilder chain = this.getAcceptor().getFilterChain();
			ObjectSerializationCodecFactory objscf = new ObjectSerializationCodecFactory();
			ProtocolCodecFilter protocolCodecFilter = new ProtocolCodecFilter(objscf);
			chain.addLast("myTextChain", protocolCodecFilter);
			this.getAcceptor().setHandler(this.getHandlerAdapter());
			try {
				this.getAcceptor().bind(new InetSocketAddress(this.getSocket_IP(), this.getSocket_port()));
				this.setStart(true);
				result = true;
				EIMLogger.INFO("成功启动 聊天Socket");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
}
